// --------------------------------------------------------------------------------------------------------------------
// <copyright file="PresetMultipleRegistersPacket.cs" company="Microsoft Corporation">
// The MIT License (MIT)
// 
// Copyright (c) 2014, Microsoft Corporation
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//  THE SOFTWARE.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

namespace Microsoft.Robotics.Hardware.Modbus
{
    using System;
    using System.Net.Sockets;
    using System.Runtime.Serialization;

    /// <summary>
    /// Utility functions for building and parsing ModbusTCPPackets
    /// </summary>
    public static class PresetMultipleRegistersPacket
    {
        /// <summary>
        /// Number of bytes in Preset Multiple Registers packet not including data
        /// </summary>
        public const int PresetMultipleRegistersLengthWithoutData = 7;

        /// <summary>
        /// Modbus TCP function number for Preset Multiple Registers
        /// </summary>
        public const byte PresetMultipleRegistersFunctionNumber = 16;

        /// <summary>
        /// Builds a PresetMultipleRegisters request
        /// </summary>
        /// <param name="unitID">ID of the slave device.</param>
        /// <param name="addressOfFirstRegister">Address of the first register to read.</param>
        /// <param name="wordsToWriteCount">Number of 16-bit words to write.</param>
        /// <param name="transactionID">Transaction ID.</param>
        /// <param name="registerValues">Values to write to the registers.</param>
        /// <param name="buffer">Buffer (pre-allocated) to place packet into.</param>
        /// <returns> Size of packet in bytes. </returns>
        public static int BuildPresetMultipleRegistersRequest(
            byte unitID,
            ushort addressOfFirstRegister,
            ushort wordsToWriteCount,
            byte[] transactionID,
            ushort[] registerValues,
            byte[] buffer)
        {
            int currentByte = 0;

            // Robotiq S Model is little-endian, assumption we are on a big-endian
            // system so need to swaps byte order.
            buffer[currentByte++] = transactionID[1];
            buffer[currentByte++] = transactionID[0];

            ModbusTCPPacket.CopyBytesInReverseOrder(
               ModbusTCPPacket.ModbusTCPProtocolID,
               buffer,
               currentByte);

            currentByte += ModbusTCPPacket.ProtocolIdentifierByteCount;

            // Length is in bytes, not words
            ModbusTCPPacket.CopyBytesInReverseOrder(
               (ushort)(PresetMultipleRegistersLengthWithoutData + wordsToWriteCount * 2),
               buffer,
               currentByte);

            currentByte += ModbusTCPPacket.PacketLengthByteCount;

            buffer[currentByte++] = unitID;
            buffer[currentByte++] = PresetMultipleRegistersFunctionNumber;

            ModbusTCPPacket.CopyBytesInReverseOrder(
               addressOfFirstRegister,
               buffer,
               currentByte);

            currentByte += ModbusTCPPacket.RegisterAddressByteCount;

            // word count
            ModbusTCPPacket.CopyBytesInReverseOrder(
               wordsToWriteCount,
               buffer,
               currentByte);

            currentByte += ModbusTCPPacket.ByteCountPerWord;

            // number of bytes to follow is simply double the number of words
            // and has only a single allocated in the packet.
            buffer[currentByte++] = (byte)(wordsToWriteCount * 2);

            for (int i = 0; i < wordsToWriteCount; ++i)
            {
                ModbusTCPPacket.CopyBytes(
                    registerValues[i],
                    buffer,
                    currentByte);

                currentByte += ModbusTCPPacket.ByteCountPerWord;
            }

            return currentByte;
        }
    }
}
